package bank.jms;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.activemq.ActiveMQConnection;

import bank.Bank;
import bank.BankDriver;


/**
 * Driver for JMS connection to the active mq instance.
 * @author Roland
 */
public class JMSDriver implements BankDriver{
	/**
	 * Representing the current bank proxy for JMS connections.
	 */
	private Bank bank = null;
	/**
	 * Connection object for the activeMQ connection.
	 */
	private QueueConnection connection;
	/**
	 * Handler for the communication with the server. 
	 */
	private JMSBankHandler jmsHandler;
	
	/**
	 * Connecting to the server.
	 * @param args
	 */
	public void connect(String[] args){
		
			
		Hashtable<String,String> properties = new Hashtable<String,String>(); 
		
		properties.put(Context.INITIAL_CONTEXT_FACTORY,  
			"org.apache.activemq.jndi.ActiveMQInitialContextFactory"); 
		properties.put(Context.PROVIDER_URL, "tcp://localhost:61616"); 
		properties.put("queue.BANK", "example.BANK"); 

		try{
			
			Context context = new InitialContext(properties); 
			 
			QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup("ConnectionFactory"); 
			Queue queue = (Queue) context.lookup("BANK");
			
			connection = factory.createQueueConnection(ActiveMQConnection.DEFAULT_USER,
					ActiveMQConnection.DEFAULT_PASSWORD);
			QueueSession session = connection.createQueueSession(false,
					QueueSession.AUTO_ACKNOWLEDGE);
									
			connection.start();
			
			jmsHandler = new JMSBankHandler(session,queue);
			bank = new JMSBank(jmsHandler);
			System.out.println("connected...");
			
		}catch(JMSException ex){
			if(connection!=null)
				try {
					connection.close();
				} catch (JMSException e) {	}
			System.out.println("Could not connect to the active mq instance:\n" + ex.getMessage());
		} catch (NamingException e) {
			System.out.println("Could not connect to the active mq instance:\n" + e.getMessage());
		}
	}
	
	/**
	 * Disconnects the connection to the server.
	 */
	public void disconnect(){
		bank = null;
		jmsHandler = null;
		try {
			connection.close();
		} catch (JMSException e) {	}
		System.out.println("disconnected...");
	}
	
	/**
	 * Gets the current bank.
	 * @return Current bank
	 */
	public bank.Bank getBank(){
		return bank;
	}
}
